import React, { useEffect, useState } from 'react'
import { useDrag, useDrop } from 'react-dnd'
import { useRecoilState } from 'recoil'
import { designerState } from '../../../store'
import './index.less'

import { IDraggable } from '../component_type'

const style = {
  border: "1px dashed #bebebe",
  cursor: "move"
};

export default function DragWrapper (props: IDraggable) {
  // const [pageData, setPageData] = useRecoilState(designerState.pageDataAtom);
  const [selectedNode, setSelectedNode] = useRecoilState(designerState.selectedNodeAtom);
  // const [clickStatus, setClickStatus] = useState(false)

  useEffect(() => {
    // console.log('DragWrapper==', selectedNode)
    // window.cd = selectedNode
  }, [selectedNode])

  const [{ opacity }, drag ] = useDrag(
    () => ({
      type: props.meta.type,
      item: {...props, type: props.meta.type},
      canDrag: function (e) {
        return true
      },
      collect: (monitor) => ({
        opacity: monitor.isDragging() ? 0.5 : 1
      })
    }),
    []
  )

  // 获取选中节点的偏移量
  const getOffset = (el: any) => {
    var _x = 0, _y = 0;
    while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
      _x += el.offsetLeft - el.scrollLeft;
      _y += el.offsetTop;
      el = el.offsetParent;
    }
    return { top: _y, left: _x };
  }

  // 获取离鼠标最近的 DragWrapper
  const getFirstDragWrapper = (e: any) => {
    var result = []
    while (e.className != 'dragWrapper') {
      result.push(e);
      e = e.parentNode;
    }
    return result.length == 0 ? e : result[result.length-1].parentNode
  }

  const onClick = function (e: any) {
    // 获取当前点击的最近的 DragWrapper
    const target = getFirstDragWrapper(e.target)
    var pos = getOffset(target)
    
    // const newSelectedNode = produce(props.config.style, (draft: any) => {
    //   draft.top = pos.top
    //   draft.left = pos.left
    //   draft.height = target.offsetHeight
    //   draft.height = target.offsetWidth
    // })

    // setSelectedNode(newSelectedNode)

    setSelectedNode({
      ...props,
      menu: {
        top: pos.top,
        left: pos.left,
        height: target.offsetHeight,
        width: target.offsetWidth,
      }
    })

    // console.log('....', selectedNode)
    // window.cd = selectedNode
    e.stopPropagation()
  }

  return (
    <div ref={ drag } style={{ ...style, opacity}} className='dragWrapper' onClick={onClick} >
      { props.children }
    </div>
  )
}